Swift4.0 string/// 在指定字符串第一次搜索结果位置前/后插入字符串
extension String {
func positionOf(sub:String, backwards:Bool)->Int {
var pos = -1
guard let inde = self.range(of: sub)?.upperBound else {
return pos
}
pos = (self.range(of: sub)?.upperBound.encodedOffset)!
}else{
pos = (self.range(of: sub)?.lowerBound.encodedOffset)!
}
return pos
}
/// 在指定字符串第一次搜索结果位置前/后插入字符串
///
/// - Parameters:
/// - sub: 指定字符串
/// - inserSourceStr: 插入字符串
/// - Returns: 字符串,为查询到sub返回self
func insertStr( sub:String, inserSourceStr:String,_ backwards:Bool = true) -> String {
let position = self.positionOf(sub: sub, backwards: backwards)
if position < 0 {
return self
}
let insertindex = self.index(self.startIndex, offsetBy: position)
var returnStr = self
returnStr.insert(contentsOf: inserSourceStr, at: insertindex)
return returnStr
}
}
直接copy即可使用